package com.ssh.demo.netty.handler;

import com.ssh.demo.helper.ByteArrHelper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName UdpSessionHandler
 * @Description TODO
 * @Author ssh
 * @Date 2021/4/12 17:05
 */
@Slf4j
@AllArgsConstructor
public class UdpSessionHandler extends SimpleChannelInboundHandler<DatagramPacket> {

    private ByteArrHelper byteArrHelper;

    /**
     * 报错触发
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("UdpServerHandler exceptionCaught" + cause.getMessage());
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
        // 接受client的消息
        final ByteBuf buf = msg.content();
        int readableBytes = buf.readableBytes();
        byte[] content = new byte[readableBytes];
        buf.readBytes(content);
        String clientMessage = new String(content,"UTF-8");
        log.info("Read clientMessage is: "+clientMessage);
        if(clientMessage.contains("7E000011007E3112121212")){
            ctx.writeAndFlush(new DatagramPacket(Unpooled.wrappedBuffer("helloClient".getBytes()),msg.sender())).sync();
        }

        String s = byteArrHelper.toHexString(content);
        System.out.println("处理参数"+s);

    }

}
